package subscriber

import (
	"context"
	"log"
	"time"
	"todolist/achievement-srv/repository"
	pb "todolist/task-srv/proto/task"
)

// 定义实现类
type AchievementSub struct {
	Repo repository.AchievementRepo
}

// 只处理完成任务一个事件
func (sub *AchievementSub) Finished(ctx context.Context, task *pb.Task) error {
	log.Printf("handler received message: %v\n", task)

	entity, err := sub.Repo.FindByUserId(ctx, task.UserId)
	if err != nil {
		return err
	}

	now := time.Now().Unix()
	if entity == nil {
		entity = &repository.Achievement{
			UserId:        task.UserId,
			Total:         1,
			Finished1Time: now,
		}
	}
	entity.Total++
	switch entity.Total {
	case 100:
		entity.Finished100Time = now
	case 1000:
		entity.Finished1000Time = now
	}
	return sub.Repo.Update(ctx, entity)
}
